package com.example.sale.Interceptor;

import com.example.sale.utils.JwtUtil;
import io.jsonwebtoken.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.security.util.SignatureFileVerifier;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTInterceptor implements HandlerInterceptor {
    private JwtUtil jwtUtil;

    @Autowired
    public JWTInterceptor(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        System.out.println("token is"+token);
        try {
            jwtUtil.parseToken(token);
            map.put("state", true);
            map.put("msg", "请求成功");
            return true;
        } catch (SignatureException e) {
            e.printStackTrace();
            // 无效签名的异常处理逻辑
            map.put("msg", "无效签名");
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            // 令牌过期的异常处理逻辑
            map.put("state", "401");
            map.put("msg", "令牌已过期");
            map.put("state",401);
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
            // 不支持的令牌异常处理逻辑
            map.put("msg", "不支持的令牌");
        } catch (MalformedJwtException e) {
            e.printStackTrace();
            // 无效的令牌异常处理逻辑
            map.put("msg", "无效的令牌");
        } catch (Exception e) {
            e.printStackTrace();
            // 其他异常处理逻辑
            map.put("msg", "令牌验证失败");
        }
        map.put("state", false);
        // 将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}